<?php
//4
function online_agent_add_page() {
    return drupal_get_form('online_agent_edit_form');
}

function online_agent_edit_page($id) {
    return drupal_get_form('online_agent_edit_form', $id);
}

function online_agent_edit_form($form, &$form_state)
{
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = online_agent_load($id);
        if (empty($record)) {
            drupal_set_message(t('沟通交互人员不存在！'), 'status', FALSE);
            drupal_goto('manage_chat/agent/list');
        }
    }
    $form['online_agent_id'] = array('#type' => 'hidden', '#default_value' => $id);
    $agentmen = db_select('employee', 'E')
        -> fields('E',array('employee_id', 'employee_name'))
        -> execute();
    $agentman_options[] = '--客服名称--';
    foreach ($agentmen as $agentman) {
        $agentman_options[$agentman->employee_id] = $agentman->employee_name;
    }

    $form['uid'] = array(
            '#title' => '客服名称',
            '#type' => 'select',
            '#options' => $agentman_options,
            '#default_value' => !empty($record) ? $record->uid : '',
            '#required' => TRUE,
            '#disabled' => (!empty($record)) ? true :false,
        );
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 3, FALSE, (!empty($record))?$record->addr_id:'','省,市,县必填');
    $form['div']['#markup'] = "<div class = 'agent-add-form'>";
    $group_options[2] = '咨询';
    $group_options[3] = '投诉';
    $form['chat_group_id'] = array(
        '#title' => '客服分类',
        '#type' => 'select',
        '#options' => $group_options,
        '#default_value' => !empty($record) ? $record->chat_group_id : '',
        '#required' => TRUE,
        '#disabled' => (!empty($record)) ? true :false,
    );
    $form['alias'] = array(
        '#title' => '客服别名',
        '#type' => 'textfield',
        '#size' => 32,
        '#maxlength' => 32,
        '#default_value' =>'',
        '#required' => TRUE,
    );
    $form['div_close']['#markup'] = "</div>";
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
        '#access' => online_agent_submit($form_state, $id),
        '#validate' => array('online_agent_edit_form_validate'),
    );

    return $form;
}

function online_agent_edit_form_validate($form, &$form_state) {
    _address_element_validate($form_state);
    if(empty($form_state['values']['chat_group_id'])){
        form_set_error('chat_group_id','请选择服务类型');
    }
    if(empty($form_state['values']['uid'])){
        form_set_error('uid','客服名称不能为空');
    }
}

function online_agent_edit_form_submit($form, &$form_state)
{
    global $user;
    $online_agent_id = $form_state['values']['online_agent_id'];
    $uid = $form_state['values']['uid'];
    $addr_id =  _get_address_id_from_autocomplete_select($form_state);

    $chat_group_id = $form_state['values']['chat_group_id'];
    $alias = $form_state['values']['alias'];
    $author_uid = $user->uid;
    $timestamp = time();
    $transaction = db_transaction();
    try {
        if (empty($online_agent_id)) {
            // create agent
            $recode = online_agent_check($uid, $addr_id, $chat_group_id);
            if (empty($recode)) {
                $nid = db_insert('online_agent')
                    ->fields(array(
                        'uid' => $uid,
                        'addr_id' => $addr_id,
                        'chat_group_id'=>$chat_group_id,
                        'alias'=>$alias,
                        'author_uid' => $author_uid,
                        'timestamp' => $timestamp,
                    ))
                    ->execute();
                if($nid > 0){
                    drupal_set_message('添加成功', 'status', FALSE);
                }
            } else {
                drupal_set_message('该人员已作为选中服务类型分配到选中地区', 'error', FALSE);
            }
        } else {
            // update agent
            db_update('online_agent')
                ->condition('online_agent_id', $online_agent_id)
                ->fields(array(
                    'uid' => $uid,
                    'addr_id' => $addr_id,
                    'alias' => $alias,
                    'author_uid' => $author_uid,
                    'timestamp' => $timestamp,

                ))
                ->execute();
            drupal_set_message('更新成功', 'status', FALSE);
        }
    }catch (Exception $e){
        $transaction->rollback();
    }
}

function online_agent_submit(&$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;

    if ($id) {
        //edit
        $agent = online_agent_load($id);
        if ($agent) {
            if ($agent->author_uid == $user->uid) {
                return TRUE;
            } else {
                return user_access('manage online_agent');
            }
        } else {
            //load false
            drupal_set_message(t('客服人员不存在！'), 'status', FALSE);
        }
    } else {
        //add
        return user_access('manage online_agent');
    }
}


function online_agent_load($id) {
    $result = db_select('online_agent', 'OA')
        -> fields('OA')
        -> condition('OA.online_agent_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}

function online_agent_check($uid, $addr_id, $chat_group_id){
   $result = db_select('online_agent','OA')
    ->fields('OA')
    ->condition('OA.uid',$uid, '=')
    ->condition('OA.addr_id',$addr_id, '=')
    ->condition('OA.chat_group_id',$chat_group_id, '=')
    ->execute()
    ->fetchObject();
    return $result;
}
//
//function insert_chat_for_farmer($user_id,$nickname,$addr_id,$chat_group_id){
//    $farmer_ids = get_farmerids_byaddr($addr_id);
//    foreach($farmer_ids as $farmer_id){
//        $isset_chat = isset_chat_user_load($user_id,$farmer_id['farmer_id']);
//        if(!$isset_chat){
//            $chat_id = db_insert('chat')
//                ->fields(array(
//                    'title' =>$user_id."&".$farmer_id['farmer_id'],
//                    'timestamp' => 0,
//                    'type' => 0,
//                    'active' => 1))
//                ->execute();
//            $add_user = db_insert('chat_users')
//                ->fields(array(
//                    'chat_id' => $chat_id,
//                    'user_id' => $user_id,
//                    'nickname' => $nickname,
//                    'chat_group_id'=>$chat_group_id,
//                    'active' => 1,
//                    'checkpoint' => 0))
//                ->execute();
//            $add_user1 = db_insert('chat_users')
//                ->fields(array(
//                    'chat_id' => $chat_id,
//                    'user_id' => $farmer_id['farmer_id'],
//                    'nickname' => $farmer_id['farmer_name'],
//                    'chat_group_id' =>$chat_group_id,
//                    'active' => 1,
//                    'checkpoint' => 0))
//                ->execute();
//        }
//    }
//}
//
//function get_farmerids_byaddr($addr_id){
//    $addr_ids = get_SonAddr_id($addr_id);
//    $query = db_select('farmer','F');
//    $query->condition('F.addr_id',$addr_ids,'in');
//    $query->fields('F',array('farmer_id','farmer_name'));
//    $res = $query->execute()->fetchAll();
//    foreach($res as $row){
//        $result[$row->farmer_id]['farmer_id'] = $row->farmer_id;
//        $result[$row->farmer_id]['farmer_name'] = $row->farmer_name;
//    }
//    return $result;
//}
